from django.views.decorators.csrf import csrf_exempt
from django.db import transaction
from app.model.MessageModel import MessageSerializers,QyMessage
from app.model.ReplayModel import QyReply
from base.myjson import JSONResponse
from base.my_page import mypage
from base.Var import appid,appsecret
from base.wechat_sdk.basic import WechatBasic
from base.mybase64 import MyFile
import json,time



@csrf_exempt
def getMessageAll(request):
    '''
    所有与指定活动相关的留言
    :param request:
    :return:
    '''
    if request.method == 'GET':
        page = request.GET.get('page')
        activity_id = request.GET.get('activity')
        objs = QyMessage.objects.filter(activity_id=activity_id)

        p = mypage(page, objs)
        obj = p['page_list']
        total = p['page_sum']

        serializer = MessageSerializers(obj,many=True)
        return JSONResponse(0,serializer.data,total)
    else:
        return JSONResponse(1054)



@csrf_exempt
def createMessage(request):
    '''
    用户创建留言
    :param request:
    :return:
    '''
    if request.method == 'POST':
        data = json.loads(request.body)
        with transaction.atomic():
            if data.get('media_id'):
                obj = WechatBasic(appid=appid, appsecret=appsecret)
                response = obj.download_media(data.get('media_id'))
                file, path = MyFile().Picture_download(response)
            else:
                path = ''
        try:
            obj = QyMessage(
                activity_id = data.get('activity_id'),
                member_id= data.get('member_id'),
                message_content = data.get('message_content'),
                message_img = path,
                add_time = str(time.time())
            )
            obj.save()
            return JSONResponse(0)
        except:
            return JSONResponse(1001)
    else:
        return JSONResponse(1055)




@csrf_exempt
def delete_message(request):
    '''
    删除留言
    :param request:
    :return:
    '''
    if request.method == 'POST':
        try:
            message_id = request.GET.get('message')
            QyMessage.objects.get(pk=message_id).delete()
            QyReply.objects.filter(message_id = message_id).delete()
            return JSONResponse(0)
        except:
            return JSONResponse(1001)
    else:
        return JSONResponse(1055)